<template>
  <div>
    <el-table
            border
            show-summary
            ref="multipleTable"
            :data="shoppingList"
            tooltip-effect="dark"
            style="width: 900px">
      <el-table-column
              type="selection"
              width="55">
      </el-table-column>
      <el-table-column prop="classes" label="课程" align="center"> </el-table-column>
      <el-table-column prop="quantity" label="数量" align="center">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.quantity" size="mini" :min="1" :step="1" @change="quantityChange" step-strictly></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="单价" align="center"></el-table-column>
      <el-table-column prop="allPrice" label="总价" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="danger" @click="deleteIndex(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>

export default {
  name: 'ShoppingCart',
  data() {
      return {
        formInline: {
          name: '',
          price: ''
        },
        buttonName:"新增",
        shoppingList: [],
        tableIndex:0,
      }
  },
  created(){
    this.getShoppingList();
  },
  methods:{
    deleteIndex(index){
      this.shoppingList.splice(index,1)
      this.quantityChange()
      this.sethoppingList();
    },

    getShoppingList() {
      if (localStorage.getItem("shoppingList")) {
        try {
          this.shoppingList = JSON.parse(localStorage.getItem("shoppingList"));
        } catch (error) {
          console.log(error);
          localStorage.setItem(
            "shoppingList",
            JSON.stringify(this.shoppingList)
          );
        }
      } else {
        localStorage.setItem("shoppingList", JSON.stringify(this.shoppingList));
      }
    },

    sethoppingList(){
      localStorage.setItem("shoppingList", JSON.stringify(this.shoppingList));
      localStorage.setItem("shoppingCount",this.$parent.shoppingCount);
    },

    quantityChange(){
      let count = 0;
      this.shoppingList.forEach( item =>{
          item.allPrice = item.quantity * item.price;
          count+=item.quantity;
      });
      this.$parent.shoppingCount = count;
      this.sethoppingList();
    },

  },
}
</script>

<style scope>
  
</style>